import {
  getProductBomOverviewByPage,
  addProductBomOverview,
  updateProductBomOverview,
  delProductBomOverview,
  exportProductBomOverview,
  getProductBomOverviewByBatchProductId,
  addBomByTemplate,
  downloadBomTemplate,
  downloadFile,
  change,
  getMax,
  downloadStandardBom,
} from '@/services/design/productBomOverview';
import { viewBaseInfo } from '@/services/product/productManufactInforExecute';
import { addBomReview } from '@/services/design/bomReview';
import { Ellipsis } from '@/components/Ellipsis';
import {
  PlusOutlined,
  UploadOutlined,
  LogoutOutlined,
  DownOutlined,
  DownloadOutlined,
  ArrowLeftOutlined,
  SaveOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-components';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Upload,
  InputNumber,
  Row,
  Col,
  Select,
  Card,
  Tabs,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import type { recordInfoType } from './components/interfaceProduct';
import ProductDrawingInfo from './productDrawingInfo';
import '@/pages/design/style.less';
const ProductBomOverview: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [modalVisit2, setModalVisit2] = useState(false);
  const [confirmLoading2, setConfirmLoading2] = useState(false);
  const [createOrUpdate2, setCreateOrUpdate2] = useState(false); //编辑框的disable
  const [file, setFile] = useState();
  const [recordInfo, setRecord] = useState<recordInfoType>();
  const [form] = Form.useForm();
  const ref = useRef(null);

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);

  const [ischange, setischange] = useState(false); //设置编辑按钮是否启用
  const [theversion, setversion] = useState(''); // 版本筛选
  const [allversion, set_allversion] = useState([]); // 版本筛选

  const [id_list, setid_list] = useState([]); // 保存修改的id

  const [rowSelection, setRowSelection] = useState([]); //批量操作中的选中

  type DataSourceType = {
    id: React.Key;
    title?: string;
    readonly?: string;
    decs?: string;
    state?: string;
    created_at?: number;
    update_at?: number;
    children?: DataSourceType[];
    changeStatus?: number;
  };

  const columns: ProColumns<DataSourceType>[] = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   valueType: 'index',
    //   width: 80,
    // },
    {
      title: 'BOM编号',
      dataIndex: 'bomCode',
      width: 190,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '是否最高版本',
      dataIndex: 'isMax',
      hideInTable: true,
      search: false,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <>{record.isMax == 1 ? '是' : '否'}</>;
      },
      readonly: true,

      defaultSortOrder: 'descend',
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      width: 150,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      width: 200,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      width: 200,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '数量',
      dataIndex: 'materialQty',
      width: 80,
      align: 'center',
      sorter: true,
      valueType: 'digit',
      render: (text) => <>{Ellipsis(text)}</>,
      editable: (text, record, index) => {
        return true;
      },
      renderFormItem: ({ index }) => {
        return <InputNumber type="number" precision={0} min={0} placeholder="请输入正整数" />;
      },

      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '此项是必填项'
      //     }
      //   ],
      // },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 80,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '位置号',
      dataIndex: 'positionNo',
      width: 200,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料品牌',
      dataIndex: 'brand',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料分类',
      dataIndex: 'materialClassification',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料种类',
      dataIndex: 'materialType',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '是否甲供料',
      dataIndex: 'isJia',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '产品/柜体编号',
      dataIndex: 'productCode',
      width: 210,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '归档标识',
      dataIndex: 'archiveFlag',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.archiveFlag == 1 ? '已归档' : '未归档'}</div>;
      },
      readonly: true,
    },
    // {
    //   title: '产品编号',
    //   dataIndex: 'partCode',
    //   readonly: true,
    // },
    // {
    //   title: '变更状态',
    //   dataIndex: 'changeStatus',
    //  align: 'center',sorter: true,
    //   render: (text, record, _, action) => {
    //     return <div>{record.changeStatus == 1 ? '已变更' : '未变更'}</div>;
    //   },
    //   readonly: true,
    // },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   key: 'option',
    //   fixed: 'right',
    //   width: 90,
    //   render: (text, record, _, action) => [
    //     <a
    //       key="editable"
    //       hidden={history.location.state.reviewState == 1}
    //       disabled={(!ischange || record.isMax == 0) && history.location.state.reviewState == 2}
    //       onClick={() => {
    //         if (
    //           history.location.state.reviewState == 0 ||
    //           history.location.state.reviewState == 3
    //         ) {
    //           // 待审批或者已审批状态，可以随意修改bom
    //           setModalVisit(true);
    //           setCreateOrUpdate(true);
    //           setFormTitle('编辑');
    //           form.setFieldsValue({
    //             archiveFlag: record.archiveFlag,
    //             bomCode: record.bomCode,
    //             bomSequence: record.bomSequence,
    //             changeStatus: record.changeStatus,
    //             isolation: record.isolation,
    //             materialCode: record.materialCode,
    //             materialName: record.materialName,
    //             materialQty: record.materialQty,
    //             materialSpec: record.materialSpec,
    //             partCode: record.partCode,
    //             positionNo: record.positionNo,
    //             productCode: record.productCode,
    //             tenantId: record.tenantId,
    //             unit: record.unit,
    //             id: record.id,
    //             brand: record.brand,
    //             materialClassification: record.materialClassification,
    //             materialType: record.materialType,
    //             isJia: record.isJia,
    //             isMax: record.isMax,
    //           });
    //         } else if (ischange && record.isMax == 1) {
    //           action?.startEditable?.(record.id);
    //         }
    //       }}
    //     >
    //       编辑
    //     </a>,
    //   ],
    // },
  ];

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: 'BOM',
      content: (
        <>
          <ProTable<DataSourceType>
            rowKey="id"
            search={false}
            headerTitle="BOM清单"
            actionRef={actionRef} //用于触发刷新操作等，看api
            // maxLength={5}到了最大行数，新建按钮消失
            recordCreatorProps={false}
            // loading={false}
            rowSelection={rowSelection}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="back_button"
                icon={<ArrowLeftOutlined />}
                onClick={() => {
                  history.push({
                    pathname: '/design/productDesign',
                    query: {
                      tab_state: history.location.state.reviewState, //传参
                    },
                  });
                }}
                type="primary"
              >
                返回
              </Button>,
              <Button
                key="bom_button"
                hidden={
                  history.location.state.reviewState == 2 || history.location.state.reviewState == 3
                }
                icon={<DownloadOutlined />}
                onClick={() => {
                  downloadStandardBom(null).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `BOM导入模板.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                下载BOM模板
              </Button>,
              <Button
                key="bom_upload_button"
                hidden={
                  history.location.state.reviewState == 1 ||
                  history.location.state.reviewState == 2 ||
                  history.location.state.reviewState == 3
                }
                icon={<UploadOutlined />}
                onClick={() => {
                  setCreateOrUpdate2(true);
                  setModalVisit2(true);
                }}
                type="primary"
              >
                BOM上传
              </Button>,
              // <Button
              //   key="add_button"
              //   hidden={history.location.state.reviewState == 1}
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     setCreateOrUpdate(false);
              //     setFormTitle('新建');
              //     form.resetFields();
              //     setModalVisit(true);
              //   }}
              //   type="primary"
              // >
              //   新增
              // </Button>,
              <Button
                hidden={
                  history.location.state.reviewState == 0 ||
                  history.location.state.reviewState == 1 ||
                  history.location.state.reviewState == 3
                }
                key="change_button"
                type="primary"
                onClick={() => {
                  setischange(true);
                }}
              >
                变更
              </Button>,
              <Button
                hidden={
                  history.location.state.reviewState == 0 ||
                  history.location.state.reviewState == 1 ||
                  history.location.state.reviewState == 3
                }
                key="save_button"
                type="primary"
                onClick={async () => {
                  if (ischange == false) {
                    message.warning('请先进行变更');
                  } else {
                    const ids = Array.from(new Set(id_list)); //去除重复的id（多次保存的情况）
                    const nums: any[] = [];
                    for (let i = 0; i < ids.length; i++) {
                      const current_data = dataSource.filter((item: any) => {
                        return item.id == ids[i];
                      });
                      nums.push(current_data[0].materialQty);
                    }
                    // const thedata = dataSource.filter((item: any) => {
                    //   return item.isMax == 1;
                    // });
                    // thedata.map((item: any, index: any) => {
                    //   ids.push(item.id);
                    //   nums.push(item.materialQty);
                    // });
                    console.log(ids, nums, '接口数据');
                    if (ids.length == 0) {
                      message.warning('没有修改的BOM');
                      setischange(false);
                    } else {
                      const result = await change({ ids, nums });
                      if (result != null) {
                        message.success('提交审批成功');
                        setid_list([]);
                        setischange(false);
                      }
                    }
                  }
                }}
              >
                提交
              </Button>,
              <Button
                key="export_button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filter_ref = { productCode: history.location.state.productCode };
                  const filters = filterTran(filter_ref);
                  exportProductBomOverview({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `ProductBomOverview.xlsx`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            scroll={{ x: 2200, y: 500 }}
            columns={columns}
            request={async (params = {}, sort, filter) => {
              // console.log(history.location.state.batchProductId );
              const res = {
                ...params,
                productCode: history.location.state.productCode,
                version: theversion,
              };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const result = await getProductBomOverviewByPage({
                ...params,
                current: 1,
                pageSize: 100,
                sorters: sorters,
                filters: filters,
              });
              // console.log(result.data.content);
              // 获取bom版本
              const result_version = await getMax({
                productCode: history.location.state.productCode,
              });
              const get_version = [];
              get_version.push({ label: '全部', value: '' });
              for (let i = 1; i <= result_version.data; i++) {
                get_version.push({ label: 'V' + String(i), value: i });
              }
              console.log(result.data.content);
              set_allversion(get_version);
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            value={dataSource}
            onChange={setDataSource}
            editable={{
              type: 'multiple',
              editableKeys,
              onSave: async (rowKey, data, row) => {
                // console.log(rowKey,'', data,'更新后的data', row,'更新前的data');
                // await waitTime(2000);
                setid_list((current) => [...current, data.id]);
              },
              onChange: setEditableRowKeys,
              actionRender: (row, config, defaultDom) => {
                return [defaultDom.save, defaultDom.cancel];
              },
            }}
          />
        </>
      ),
    },
    {
      name: 'tab2',
      label: '图纸',
      content: <ProductDrawingInfo></ProductDrawingInfo>,
    },
  ];

  // 新增BOM
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = { ...form.getFieldsValue() };
          res.productCode = history.location.state.productCode;
          res.isMax = 1;
          res.version = 1;
          if (history.location.state.reviewState == 0 || history.location.state.reviewState == 3) {
            //待审批或驳回页面的新增
            const result = await addProductBomOverview(res);
            if (result != null) {
              message.success('添加成功');
            }
          } else {
            //已审批页面的新增
            const getuserlist = await viewBaseInfo(null);
            res.userName = getuserlist.data.name;
            res.changeStatus = 0;
            res.changeSuccess = 0;
            res.projectName = history.location.state.projectName;
            console.log(res);
            const result = await addBomReview(res);
            if (result != null) {
              message.success('提交审批成功');
              form.resetFields();
            }
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          // 编辑
          const res = { ...form.getFieldsValue() };
          res.changeStatus = 1;
          console.log(res, '编辑接口数据');
          // res.productCode = recordInfo?.productCode;
          // res.bomCode = recordInfo?.bomCode;
          // res.bomSequence  = recordInfo?.bomSequence;
          // res.materialCode = recordInfo?.materialCode;
          // res.unit  = recordInfo?.unit;
          // res.isolation = recordInfo?.isolation;
          // res.archiveFlag = recordInfo?.archiveFlag;
          const result = await updateProductBomOverview(res);
          if (result != null) {
            message.success('修改成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  // BOM上传
  const handleSubmit2 = async () => {
    try {
      const res = { ...form.getFieldsValue() };
      const formData = new window.FormData();
      console.log(res.file.fileList);
      res.file.fileList.map((file: any) => {
        formData.append('file', file.originFileObj);
      });
      res.file = formData;
      res.productCode = history.location.state.productCode;
      res.batchProductId = history.location.state.batchProductId;
      console.log(res);
      const result = await addBomByTemplate(res);
      if (result != null && result.code == 0) {
        message.success('上传成功');
        form.resetFields();
      } else if (result != null && result.code == 110) {
        message.warning('请正确使用模板');
        form.resetFields();
      }
      setConfirmLoading2(false);
      setModalVisit2(false);
      actionRef.current!.reload();
    } catch (error) {
      console.log(error);
    }
  };

  const onFilesChange = async (file) => {
    setFile(file);
  };
  const beforeUpload = (file) => {
    setFile(file);
    return false;
  };

  const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        destroyInactiveTabPane
        type="card"
        animated={true}
        style={{ background: 'white' }}
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        width={800}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '95px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="archiveFlag" name="archiveFlag" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="bomCode" name="bomCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="bomSequence" name="bomSequence" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="changeStatus" name="changeStatus" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="isolation" name="isolation" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="partCode" name="partCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="productCode" name="productCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="tenantId" name="tenantId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label="isMax" name="isMax" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="物料编号"
                name="materialCode"
                rules={[{ required: true, message: '请输入物料编号!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料名称" name="materialName">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="物料规格"
                name="materialSpec"
                rules={[{ required: true, message: '请输入物料规格!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料分类" name="materialClassification">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item label="物料种类" name="materialType">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="物料品牌" name="brand">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="BOM数量"
                name="materialQty"
                rules={[{ required: true, message: '请输入BOM数量!' }]}
              >
                <InputNumber min={0} precision={0} style={{ width: 255 }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="物料单位"
                name="unit"
                rules={[{ required: true, message: '请输入物料单位!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="位置号"
                name="positionNo"
                rules={[{ required: true, message: '请输入位置号!' }]}
                // hidden={!createOrUpdate}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="是否甲供料"
                name="isJia" //
              >
                <Select
                  placeholder="请选择是否甲供料"
                  onChange={() => {}}
                  options={[
                    { value: '是', label: '是' },
                    { value: '否', label: '否' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        title="上传BOM文件"
        visible={modalVisit2}
        onOk={handleSubmit2}
        confirmLoading={confirmLoading2}
        onCancel={() => setModalVisit2(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="上传BOM"
            name="file"
            rules={[{ required: true, message: '请上传BOM文件!' }]}
          >
            <Upload
              accept="application"
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
              multiple
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default ProductBomOverview;
